//
//  NetworkMonitor.swift
//  Mediaplayer
//
//  Created by bin hu on 2025/7/11.
//

import UIKit
import SystemConfiguration

// MARK: - 网络监控
enum NetworkType {
    case wifi
    case cellular
    case unknown
}

protocol NetworkMonitorDelegate: AnyObject {
    func networkStatusChanged(type: NetworkType)
}

class NetworkMonitor {
    static let shared = NetworkMonitor()
    private let reachability = SCNetworkReachabilityCreateWithName(nil, "www.baidu.com")
    private var flags: SCNetworkReachabilityFlags?
    private var timer: DispatchSourceTimer?
    
    var currentNetworkType: NetworkType = .unknown
    weak var delegate: NetworkMonitorDelegate?
    
    private init() {}
    
    func startMonitoring() {
        stopMonitoring()
        
        timer = DispatchSource.makeTimerSource(queue: .global())
        timer?.schedule(deadline: .now(), repeating: .seconds(5))
        timer?.setEventHandler { [weak self] in
            self?.checkNetworkStatus()
        }
        timer?.resume()
        
        // 立即检查一次
        checkNetworkStatus()
    }
    
    func stopMonitoring() {
        timer?.cancel()
        timer = nil
    }
    
    private func checkNetworkStatus() {
        var flags = SCNetworkReachabilityFlags()
        SCNetworkReachabilityGetFlags(reachability!, &flags)
        
        let newType: NetworkType
        if flags.contains(.reachable) {
            if flags.contains(.isWWAN) {
                newType = .cellular
            } else {
                newType = .wifi
            }
        } else {
            newType = .unknown
        }
        
        // 只有类型变化时才通知
        if newType != currentNetworkType {
            currentNetworkType = newType
            DispatchQueue.main.async {
                self.delegate?.networkStatusChanged(type: newType)
            }
        }
    }
}
